﻿<#
.SYNOPSIS
	Script will remove old IIS logs to free up disk space
.DESCRIPTION
	Script will remove IIS logs older than a configured number of days from the servers listed.  Can be scheduled.
.PARAMETER none
.NOTES
	Name: Remove-OldIISLogs
	Author: David Ray
	DateCreated: 2011Feb3
#>

#Array of servernames
$ServerList = @("Chw-msg-301","chw-msg-302","chw-msg-302","Chw-msg-401","chw-msg-402","chw-msg-402","chw-msg-011","chw-msg-821","chw-msg-822","chw-msg-823","chw-msg-824","chw-owa-011","chw-cas-001","chw-cas-002") 
#Number of Days of logs to keep (Older will be deleted)
$DaystoKeep = 60


Function Get-IISLogLocation {
<#
.SYNOPSIS
    This function can be ran against a server or multiple servers to locate
    the log file location for each web site configured in IIS.
.DESCRIPTION
    This function can be ran against a server or multiple servers to locate
    the log file location for each web site configured in IIS.
.PARAMETER computer
    Name of computer to query log file location.
.NOTES
    Name: Get-IISLogLocation
    Author: Boe Prox
    DateCreated: 11Aug2010  

.LINK   

http://boeprox.wordpress.com

.EXAMPLE
Get-IISLogLocation -computer 'server1' 

Description
-----------
This command will list the IIS log location for each website configured on 'Server1' 

#>
[cmdletbinding(
    SupportsShouldProcess = $True,
    DefaultParameterSetName = 'computer',
    ConfirmImpact = 'low'
)]
param(
    [Parameter(
        Mandatory = $False,
        ParameterSetName = 'computer',
        ValueFromPipeline = $True)]
        [string[]]$computer
)
Begin {
    $report = @()
    }
Process {
    ForEach ($c in $Computer) {
            Write-Verbose "Checking connection on $($c)"

            If (Test-Connection -comp $c -count 1) { 

                Write-Verbose "Making IIS connection to $($c)"
                $sites = [adsi]"IIS://$c/W3SVC"
                $children = $sites.children
                ForEach ($child in $children) {
                    Write-Verbose "Checking $child.servercomment"
                    If ($child.KeyType -eq "IIsWebServer") {
                        Write-Verbose "Found site"
                        $temp = "" | Select-Object Server, WebSite, LogLocation, Name
                        $temp.Server = $c
                        $temp.WebSite = $child.ServerComment
                        $temp.LogLocation = $child.LogFileDirectory
						$temp.Name = $child.Name
                        $report += $temp
                        }
                    }
            }
        }
    }
End {
    $report
    }
}

## Main


Foreach ($Server in $ServerList) {
	$Sites = Get-IISLogLocation -computer $Server 
	Foreach ($Site in $Sites) {
		Get-ChildItem ("\\"+$Site.Server+"\"+($Site.LogLocation.ToString()+"\W3SVC"+$Site.Name).Replace(":","$")) | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-$DaystoKeep)} | Remove-Item 
	}
}